<template>
  <div v-if="cartList.length > 0">
      <el-row class="title">
        <el-col :span="2">
            <el-checkbox v-model="checkAllState" :indeterminate="halfState" @change="checkAllOrNone" label="全选" />
        </el-col>
        <el-col :span="11">商品</el-col>
        <el-col :span="2">单价</el-col>
        <el-col :span="6">数量</el-col>
        <el-col :span="2">小计</el-col>
        <el-col :span="1">操作</el-col>
      </el-row>
      <el-row v-for="(cart,index) in cartList" :key="index" class="cartItem">
        <el-col :span="2">
          <el-checkbox v-model="cart.checkState" @change="checkStateChange"  />
        </el-col>
        <el-col :span="2">
            <el-image :src="`${SERVER_ADDR}/goods/pic/${cart.goods.picList[0].url}`"
            style="height: 50px; width: 50px" fit="contain" />
        </el-col>
        <el-col :span="5">{{cart.goods.name}}</el-col>
        <el-col :span="4">{{cart.goods.color}}- {{cart.goods.version}} </el-col>
        <el-col :span="2">{{cart.goods.price.toFixed(2)}}</el-col>
        <el-col :span="6">
          <el-input-number
              v-model="cart.count"
              :min="1" size="small"
              @change="updateCount(cart)"/>
        </el-col>
        <el-col :span="2">{{cart.goods.price * cart.count}}</el-col>
        <el-col :span="1">
          <el-button type="danger" :icon="Delete" circle @click="deleteById(cart.id)"/>
        </el-col>
      </el-row>
      <el-row class="cartFooter">
        <el-col :span="2">
          <el-checkbox v-model="checkAllState" :indeterminate="halfState" @change="checkAllOrNone" label="全选" />
        </el-col>
        <el-col :span="3">
          <el-link @click="deleteChecked">删除选中商品</el-link>
        </el-col>
        <el-col :span="11">
          <el-link @click="clearCart">清空购物车</el-link>
        </el-col>
        <el-col :span="3">
          已选择{{checkedCount}}商品
        </el-col>
        <el-col :span="3">
          总价: ￥{{total.toFixed(2)}}
        </el-col>
        <el-col :span="2" >
          <el-button type="danger" @click="goToCreatOrder" >结算</el-button>
        </el-col>
      </el-row>
  </div>
  <div v-else class="none">
      还没有心仪的商品，快去看看吧
    <router-link to="/user/index">去购物</router-link>
  </div>

</template>

<script setup>
import {ref} from "vue";
import cartApi from "@/api/cartApi.js";
import {Delete} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
const router = useRouter()
//当前用户所有的购物车信息
const cartList = ref([])
//服务器的地址
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR)
//全选按钮是否选中
const checkAllState = ref(false)
//没有全选的状态
const halfState = ref(false)
//选中·商品的数量·
const checkedCount = ref(0);
//选中商品的总金额
const total = ref(0);
//跳转到生成订单页面
function goToCreatOrder(){
  //获取已选择的购物车的id
  let cartIds = [];
  cartList.value.forEach(cart=>{
    if(cart.checkState){
      cartIds.push(cart.id)
    }
  })
  if(cartIds.length == 0){
    ElMessage.warning("请先选择商品")
    return;
  }
  router.push({
    path: "/user/creatOrder",
    query:{
      cartIds
    }

  })
}
//查询当前用户所有的购物车信息
function selectCartList(){
  cartApi.selectCartList().then(resp=>{
    cartList.value = resp.data;
  })

}
//全选或者全不选
function checkAllOrNone(){
  //让每个购物车前面多选按钮的状态和全选按钮的状态保持一致
  cartList.value.forEach(cart=>{
    cart.checkState = checkAllState.value;
  })
  calcCheckedCountAndTotal()
}
//购物车前面的多选按钮状态发生变化时调用的函数
function checkStateChange() {
  let count = 0; //被选中的数量
  cartList.value.forEach(cart => {
    if (cart.checkState) {
      count++;

    }
  });
  if (count == cartList.value.length) {
    checkAllState.value = true;
    halfState.value = false;
  } else if (count == 0){
    checkAllState.value = false;
    halfState.value = false;
  } else {

    halfState.value = true;
  }
  calcCheckedCountAndTotal()
}
//计算选中商品的数量和金额
function calcCheckedCountAndTotal() {
  checkedCount.value = 0;
  total.value = 0;
  cartList.value.forEach(cart => {
    if (cart.checkState) {
      checkedCount.value += cart.count;
      total.value += cart.goods.price * cart.count;
    }
  });
}


//根据id删除
function deleteById(id){
  cartApi.delete(id).then(resp=>{
      if (resp.code==10000){
        ElMessage.success(resp.msg)
        //将被删除的项从cartList中清除
        cartList.value = cartList.value.filter(cart => cart.id != id)
        //设置全选按钮的状态
        checkStateChange()
        calcCheckedCountAndTotal()
      } else {
        ElMessage.error(resp.msg)
      }
  })
}
//修改购物车商品的数量
function updateCount(cart) {
  cartApi.update({id: cart.id, count: cart.count})
      .then(resp => {
        if (resp.code === 10000) {
          // ElMessage.success(resp.msg)
          //让购物车中商品数量和数据库中保持一致
          cartApi.selectById(cart.id)
          .then(resp => {
            cartList.value.forEach(cart => {
              if (cart.id === resp.data.id) {
                cart.count = resp.data.count
              }
            })
            calcCheckedCountAndTotal()
          })
        } else {
          ElMessage.error(resp.msg)
        }
      })
}
//清除已选择的购物车
function deleteChecked(){
  let ids = [];
  cartList.value.forEach(cart=>{
    if(cart.checkState){
      ids.push(cart.id)
    }
  });
  cartApi.deleteByIds(ids).then(resp=>{
    if(resp.code==10000){
      ElMessage.success(resp.msg)
      //将被删除的项从cartList中清除
      cartList.value = cartList.value.filter(cart=>!cart.checkState)
      //重新设置全选按钮的状态，重新计算金额和数量
      checkStateChange()
    }else {
      ElMessage.error(resp.msg)
    }
  })
}
// 清空所有
function clearCart(){
  let ids = [];
  cartList.value.forEach(cart=>{
    ids.push(cart.id)
    if(ids.length == 0){
      ElMessage.warning("购物车中没有商品")
      return
    }

  });
  cartApi.clearCart().then(resp=>{
    if (resp.code==10000){
      ElMessage.success(resp.msg)
      //刷新购物车列表
      selectCartList()
    } else {
      ElMessage.error(resp.msg)
    }
  })
}


selectCartList();
</script>

<style scoped>
    .title {
      margin: 20px 0;
      padding-left: 10px;
      font-size: 14px;
      background-color: #eeeeee;
      line-height: 40px;
      height: 40px;
    }
    .cartItem{
      margin-bottom: 5px;
      padding-left: 10px;
      font-size: 14px;
      background-color: #eeeeee;
      line-height: 50px;
      height: 50px;
    }
    .cartFooter{
      margin: 20px 0;
      padding-left: 10px;
      font-size: 14px;
      background-color: #eeeeee;
      line-height: 40px;
      height: 40px;
    }
    .none{
      text-align: center;
      background-color: #eeeeee;
      height: 400px;
    }
</style>